<template>
    <div class="dashboard content-container">
        <!-- 添加一个适度的空白区域，使内容向下移但不要太多 -->
        <div class="empty-space mb-6"></div>
        
        <!-- 头部统计卡片 -->
        <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <DashboardStatsCard 
                    icon="Document"
                    icon-color="text-blue-500"
                    icon-bg-color="rgba(64, 158, 255, 0.1)"
                    title="全站文章"
                    subtitle="网站的文章总数"
                    :value="articleTotalCount"
                    :trend="8"
                    :show-trend="true"
                    footer-text="最近更新于今天"
                />
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <DashboardStatsCard 
                    icon="Folder"
                    icon-color="text-yellow-500"
                    icon-bg-color="rgba(250, 200, 88, 0.1)"
                    title="文章分类"
                    subtitle="网站的分类总数"
                    :value="categoryTotalCount"
                    :trend="3"
                    :show-trend="true"
                    footer-text="最近更新于今天"
                />
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <DashboardStatsCard 
                    icon="PriceTag"
                    icon-color="text-green-500"
                    icon-bg-color="rgba(103, 194, 58, 0.1)"
                    title="文章标签"
                    subtitle="网站的标签总数"
                    :value="tagTotalCount"
                    :trend="5"
                    :show-trend="true"
                    footer-text="累计统计"
                />
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
                <DashboardStatsCard 
                    icon="Comment"
                    icon-color="text-purple-500"
                    icon-bg-color="rgba(154, 96, 180, 0.1)"
                    title="文章评论"
                    subtitle="网站的评论总数"
                    :value="commentTotalCount"
                    :trend="12"
                    :show-trend="true"
                    footer-text="参与度分析"
                />
            </el-col>
        </el-row>
      
        <!-- 趋势图和分布图 -->
        <el-row :gutter="20" class="mt-8">
            <el-col :xs="24" :lg="16">
                <ArticleTrendChart 
                    title="全站文章发布趋势" 
                    :weekData="articleTrendData.weekData"
                    :monthData="articleTrendData.monthData"
                    :yearData="articleTrendData.yearData"
                />
            </el-col>
            <el-col :xs="24" :lg="8">
                <ArticleDistributionChart 
                    title="全站文章分类分布" 
                    :data="categoryDistribution" 
                />
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import CountTo from '@/components/CountTo.vue'
import DashboardStatsCard from '@/components/DashboardStatsCard.vue'
import ArticleTrendChart from '@/components/ArticleTrendChart.vue'
import ArticleDistributionChart from '@/components/ArticleDistributionChart.vue'
import { ref, onMounted } from 'vue'
import { getArticlePageList } from '@/api/admin/article'
import { Document, Folder, PriceTag, View, Comment } from '@element-plus/icons-vue'
import axios from 'axios'
import { getCategoryCount, getTagCount } from '@/api/admin/dashboard'

const articleTotalCount = ref(0)
const categoryTotalCount = ref(0)
const tagTotalCount = ref(0)
const commentTotalCount = ref(0)
const pvTotalCount = ref(0)

// 文章分类分布数据
const categoryDistribution = ref([])

// 文章发布趋势数据
const articleTrendData = ref({
    weekData: {
        xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        series: [0, 0, 0, 0, 0, 0, 0]
    },
    monthData: {
        xAxis: Array.from({length: 30}, (_, i) => (i + 1) + '日'),
        series: Array.from({length: 30}, () => 0)
    },
    yearData: {
        xAxis: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        series: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    }
})

// 从文章列表计算趋势数据
const calculateArticleTrend = (articles) => {
    if (!articles || !articles.length) return false;
    
    // 创建日期映射数据结构
    const weekMap = new Map();
    const monthMap = new Map();
    const yearMap = new Map();
    
    // 初始化周数据
    const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    weekDays.forEach(day => weekMap.set(day, 0));
    
    // 初始化月数据
    for (let i = 1; i <= 30; i++) {
        monthMap.set(i, 0);
    }
    
    // 初始化年数据
    for (let i = 1; i <= 12; i++) {
        yearMap.set(i, 0);
    }
    
    // 计算当前日期，用于确定一周内的数据
    const now = new Date();
    const oneWeekAgo = new Date();
    oneWeekAgo.setDate(now.getDate() - 7);
    
    // 当前月份的第一天
    const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
    
    // 遍历文章并按日期分组
    articles.forEach(article => {
        if (!article.createTime) return;
        
        const createTime = new Date(article.createTime);
        
        // 跳过无效日期
        if (isNaN(createTime.getTime())) return;
        
        // 计算周数据 (过去一周)
        if (createTime >= oneWeekAgo && createTime <= now) {
            const dayOfWeek = createTime.getDay(); // 0是周日，1-6是周一到周六
            const dayName = weekDays[dayOfWeek === 0 ? 6 : dayOfWeek - 1]; // 转换为周一到周日
            weekMap.set(dayName, (weekMap.get(dayName) || 0) + 1);
        }
        
        // 计算月数据 (当月)
        if (createTime >= firstDayOfMonth) {
            const dayOfMonth = createTime.getDate();
            monthMap.set(dayOfMonth, (monthMap.get(dayOfMonth) || 0) + 1);
        }
        
        // 计算年数据 (本年)
        const month = createTime.getMonth() + 1; // getMonth()返回0-11
        yearMap.set(month, (yearMap.get(month) || 0) + 1);
    });
    
    // 转换为图表数据格式
    articleTrendData.value = {
        weekData: {
            xAxis: weekDays,
            series: weekDays.map(day => weekMap.get(day) || 0)
        },
        monthData: {
            xAxis: Array.from({length: 30}, (_, i) => (i + 1) + '日'),
            series: Array.from({length: 30}, (_, i) => monthMap.get(i + 1) || 0)
        },
        yearData: {
            xAxis: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
            series: Array.from({length: 12}, (_, i) => yearMap.get(i + 1) || 0)
        }
    };
    
    console.log("计算的文章趋势数据:", articleTrendData.value);
    return true;
}

// 独立的获取分类总数函数
const getCategoryCountData = async () => {
    try {
        // 使用dashboard API
        const dashboardRes = await getCategoryCount();
        if (dashboardRes && dashboardRes.success && dashboardRes.data) {
            categoryTotalCount.value = Number(dashboardRes.data);
            console.log("使用dashboardAPI获取分类总数:", categoryTotalCount.value);
            return true;
        }
        
        // 尝试普通列表接口
        const categoryRes = await axios.post("/admin/category/list", {
            current: 1,
            size: 1000
        });
        console.log("分类API响应:", categoryRes);
        
        if (categoryRes && categoryRes.data && categoryRes.data.success && categoryRes.data.data) {
            // 解析响应数据
            if (Array.isArray(categoryRes.data.data)) {
                categoryTotalCount.value = categoryRes.data.data.length;
                return true;
            } else if (categoryRes.data.data.records && Array.isArray(categoryRes.data.data.records)) {
                categoryTotalCount.value = categoryRes.data.data.total || categoryRes.data.data.records.length;
                return true;
            } else if (typeof categoryRes.data.data.total === 'number') {
                categoryTotalCount.value = categoryRes.data.data.total;
                return true;
            }
        }
        
        return false;
    } catch (error) {
        console.error("获取分类数据失败:", error);
        return false;
    }
};

// 独立的获取标签总数函数
const getTagCountData = async () => {
    try {
        // 使用dashboard API
        const dashboardRes = await getTagCount();
        if (dashboardRes && dashboardRes.success && dashboardRes.data) {
            tagTotalCount.value = Number(dashboardRes.data);
            console.log("使用dashboardAPI获取标签总数:", tagTotalCount.value);
            return true;
        }
        
        // 尝试普通列表接口
        const tagRes = await axios.post("/admin/tag/list", {
            current: 1,
            size: 1000
        });
        console.log("标签API响应:", tagRes);
        
        if (tagRes && tagRes.data && tagRes.data.success && tagRes.data.data) {
            // 解析响应数据
            if (Array.isArray(tagRes.data.data)) {
                tagTotalCount.value = tagRes.data.data.length;
                return true;
            } else if (tagRes.data.data.records && Array.isArray(tagRes.data.data.records)) {
                tagTotalCount.value = tagRes.data.data.total || tagRes.data.data.records.length;
                return true;
            } else if (typeof tagRes.data.data.total === 'number') {
                tagTotalCount.value = tagRes.data.data.total;
                return true;
            }
        }
        
        return false;
    } catch (error) {
        console.error("获取标签数据失败:", error);
        return false;
    }
};

// 获取全站所有数据统计
const getAllStatistics = async () => {
    try {
        // 获取全站文章列表
        const articleRes = await getArticlePageList({
            current: 1,
            size: 1000 // 尝试获取所有文章
        });
        
        if (articleRes && articleRes.success && articleRes.data && articleRes.data.records) {
            console.log("成功获取到全站文章列表:", articleRes.data);
            const articles = articleRes.data.records;
            
            // 设置文章总数
            articleTotalCount.value = articleRes.data.total || articles.length;
            
            // 计算文章趋势数据
            calculateArticleTrend(articles);
            
            // 计算分类分布
            const categoryMap = new Map();
            
            // 统计每个分类的文章数量
            articles.forEach(article => {
                const categoryId = article.categoryId;
                const categoryName = article.categoryName || '未分类';
                
                if (!categoryMap.has(categoryId)) {
                    categoryMap.set(categoryId, {
                        name: categoryName,
                        value: 0
                    });
                }
                
                categoryMap.get(categoryId).value += 1;
            });
            
            // 转换为数组格式
            const categoryResult = Array.from(categoryMap.values());
            console.log("从文章列表计算的分类分布:", categoryResult);
            
            // 设置分类分布数据
            if (categoryResult.length > 0) {
                categoryDistribution.value = categoryResult;
                
                // 如果从分布数据可以获得分类总数
                if (categoryTotalCount.value === 0) {
                    categoryTotalCount.value = categoryResult.length;
                }
            }
        }

        // 获取分类总数 (使用独立函数)
        await getCategoryCountData();

        // 获取标签总数 (使用独立函数)
        await getTagCountData();

        // 获取评论总数
        try {
            const commentRes = await axios.post("/admin/comment/list", {
                current: 1,
                size: 1
            });
            if (commentRes && commentRes.data && commentRes.data.success) {
                commentTotalCount.value = commentRes.data.data.total || 0;
            }
        } catch (error) {
            console.error("获取评论数据失败:", error);
            // 设置一个默认值
            commentTotalCount.value = articleTotalCount.value * 2; // 假设平均每篇文章有2条评论
        }
        
    } catch (error) {
        console.error('获取全站统计数据失败:', error);
        // 设置默认值
        setDefaultData();
    }
}

// 设置默认数据
const setDefaultData = () => {
    articleTotalCount.value = 100;
    categoryTotalCount.value = 10;
    tagTotalCount.value = 30;
    commentTotalCount.value = 200;
    
    // 默认分类分布
    categoryDistribution.value = [
        { name: 'Java开发', value: 32 },
        { name: '前端技术', value: 26 },
        { name: 'Python编程', value: 18 },
        { name: '数据库', value: 15 },
        { name: '生活随笔', value: 9 }
    ];
}

// 从文章数据中统计并提取分类和标签信息
const extractCategoryAndTagFromArticles = async () => {
    try {
        // 尝试获取全站文章，包含更多字段
        const res = await axios.post("/admin/article/list", {
            current: 1, 
            size: 1000,
            includeCategory: true,
            includeTag: true
        });
        
        if (res && res.data && res.data.success && res.data.data && res.data.data.records) {
            console.log("获取到更详细的文章数据:", res.data);
            const articles = res.data.data.records;
            
            // 1. 统计分类数据
            const categorySet = new Set();
            const categoryMap = new Map();
            
            articles.forEach(article => {
                if (article.categoryId && article.categoryName) {
                    categorySet.add(article.categoryId);
                    
                    if (!categoryMap.has(article.categoryId)) {
                        categoryMap.set(article.categoryId, {
                            name: article.categoryName,
                            value: 0
                        });
                    }
                    
                    categoryMap.get(article.categoryId).value += 1;
                }
            });
            
            // 如果分类计数为0，使用从文章中提取的数据
            if (categoryTotalCount.value === 0 && categorySet.size > 0) {
                categoryTotalCount.value = categorySet.size;
                console.log("从文章中提取分类数:", categoryTotalCount.value);
            }
            
            // 如果分类分布为空，使用从文章中提取的数据
            if (categoryDistribution.value.length === 0 && categoryMap.size > 0) {
                categoryDistribution.value = Array.from(categoryMap.values());
                console.log("从文章中提取分类分布:", categoryDistribution.value);
            }
            
            // 2. 统计标签数据
            const tagSet = new Set();
            
            articles.forEach(article => {
                if (article.tags && Array.isArray(article.tags)) {
                    article.tags.forEach(tag => {
                        if (tag && tag.id) {
                            tagSet.add(tag.id);
                        }
                    });
                }
            });
            
            // 如果标签计数为0，使用从文章中提取的数据
            if (tagTotalCount.value === 0 && tagSet.size > 0) {
                tagTotalCount.value = tagSet.size;
                console.log("从文章中提取标签数:", tagTotalCount.value);
                return true;
            }
        }
        
        return false;
    } catch (error) {
        console.error("从文章提取分类和标签失败:", error);
        return false;
    }
}

onMounted(async () => {
    // 获取全站统计数据
    await getAllStatistics();
    
    // 如果分类或标签数据为0，尝试从文章中提取
    if (categoryTotalCount.value === 0 || tagTotalCount.value === 0) {
        await extractCategoryAndTagFromArticles();
    }
    
    // 如果仍然没有数据，使用默认值
    if (categoryTotalCount.value === 0) {
        categoryTotalCount.value = 5;
    }
    
    if (tagTotalCount.value === 0) {
        tagTotalCount.value = 10;
    }
});

</script>

<style scoped>
.content-container {
    margin-top: 15px;
}

.dashboard {
    padding: 20px 24px; /* 保持内边距 */
    max-width: 1400px;
    margin: 0 auto;
}

/* 添加空白区域的样式 */
.empty-space {
    height: 20px; /* 从30px调整为20px，减少向下的空间 */
}

.mb-6 {
    margin-bottom: 24px; /* 保持24px的下边距 */
}

.mt-8 {
    margin-top: 32px;
}

.w-10 {
    width: 2.5rem!important;
}

.h-10 {
    height: 2.5rem!important;
}

/* 增加卡片间距 */
:deep(.el-card) {
    margin-bottom: 10px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05) !important;
}

/* 增加行间距 */
.el-row {
    margin-bottom: 20px !important;
}

@media (max-width: 768px) {
    .el-col {
        margin-bottom: 20px;
    }
    
    .dashboard {
        padding: 16px; /* 移动端减小内边距 */
    }
    
    /* 在移动端减少空白区域，避免过多滚动 */
    .empty-space {
        height: 10px;
    }
    
    .mb-6 {
        margin-bottom: 16px;
    }
}
</style>


